package com.microcore.event;

import com.microcore.device.model.MCSDevID;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.platform.BreakdownCheckApplication;
import org.platform.dao.mapper.FdKbEventMapper;
import org.platform.mo.db.FdKbEvent;
import org.platform.tool.util.XmlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 从文件里面插入 每个设备的 每个标准属性值
 *
 * @author FengJie
 * @date 2018/5/17
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = BreakdownCheckApplication.class)
@Slf4j
public class InsertKbEventForFile {
    private static List<String> errorList = Arrays.asList("异常", "断", "告警", "离线", "限位", "未到位", "停止", "DoubleParam");
    private static String path = "D:\\软件文件\\WeChat Files\\Fengjie1184741355\\File\\DevParam\\MY\\设备属性取值范围.txt";
    private static String devPath = "F:\\微核科技\\项目\\2018-03-07 故障诊断编码设计工作\\MYC_Devices.xml";



    @Autowired
    private FdKbEventMapper mapper;

    @Test
    public void insertForFile() throws IOException {
        FileReader fileReader = new FileReader(path);
        BufferedReader reader = new BufferedReader(fileReader);
        Map<String, String> devTypeMap = getDevType();
        String line;
        String devId = "";
        String devName = "";
        long knowledgeId = 100000;
        while ((line = reader.readLine()) != null) {
            if (isEffectiveData(line)) {
                if (isDev(line)) {
                    devId = getDevId(line);
                    devName = getDevName(line);
                } else {
                    if (isAdd(line)) {
                        FdKbEvent event = initEventByLine(devId, line);
                        event.setKnowledgeid(knowledgeId++);
                        event.setId(devId + "_" + event.getKnowledgeid());
                        event.setMonitorname(devName);
                        event.setDevicetype(devTypeMap.get(devId));

                        mapper.insert(event);

                    }

                }
            }
        }
        reader.close();
        fileReader.close();
    }

    /**
     * 判断是否有效数据
     *
     * @param line
     * @return
     */
    private boolean isEffectiveData(String line) {
        return (!"".equals(line) && !line.startsWith("属性描述") && !line.startsWith("{") && !line.startsWith("}"));
    }

    /**
     * 判断是不是设备
     */
    private boolean isDev(String line) {
        return line.startsWith("tb_mcs_");
    }


    /**
     * 获取设备名称名称
     *
     * @param line
     * @return
     */
    private String getDevId(String line) {
        String[] split = line.split("\\[");
        String s = split[0];

        int param = s.indexOf("PARAM");
        int status = s.indexOf("STATUS");
        String name = "";
        if (param != -1) {
            name = s.substring("PARAM_".length() + param);
        }
        if (status != -1) {
            name = s.substring("STATUS_".length() + status);
        }
        return name;
    }

    private String getDevName(String line) {
        int i = line.indexOf("[");
        int i1 = line.indexOf("]");
        return line.substring(i + 1, i1);
    }



    /**
     * 根据每行初始化Event
     *
     * @param line
     * @return
     */
    private FdKbEvent initEventByLine(String devId, String line) {
        FdKbEvent event = new FdKbEvent();
        //设置设备名
        event.setDeviceid(devId);
        String[] property = line.split(":");
        String name = property[0];
        String[] names = name.split("\\[");
        //得到属性名
        event.setAttrid(names[0]);
        event.setMonitorname(names[1].substring(0, names[1].length() - 1) + "异常");
        event.setGroupid(1L);
        event.setSystem("MCS");
        event.setDevicetype(devId);
        event.setModule("NA");
        event.setUnit("NA");
        event.setAffectlevel(2);

        event.setAffectdesc(getAffectdesc(line) + "异常");
        event.setAlarmreason("参数异常");
        event.setAdvise("重启设备或者维修检查");
        event.setReporttime(3L);
        event.setReportcount(3L);
        event.setStation("MYC");
        event.setAlarmtype(0);
        event.setVersion(1.0);

        //属性值
        String value = property[1];
        if (value.contains("StatusParam")) {
            event.setAttrtype(1);
            event.setLevel(2);
            String enumval = statusParam(value);
            event.setEnumval(enumval);
        }
        if (value.contains("DoubleParam")) {
            Map<String, Double> doubleMap = doubleParam(value);
            event.setAttrtype(0);
            event.setLevel(3);
            event.setMinval(doubleMap.get("min"));
            event.setMaxval(doubleMap.get("max"));
        }
        if (value.contains("[IntParam]")) {
            Map<String, Double> doubleMap = intParam(value);
            event.setLevel(3);
            event.setAttrtype(0);
            event.setMinval(doubleMap.get("min"));
            event.setMaxval(doubleMap.get("max"));
        }
        if (value.contains("[UIntParam]")) {
            Map<String, Double> doubleMap = uIntParam(value);
            event.setLevel(3);
            event.setAttrtype(0);
            event.setMinval(doubleMap.get("min"));
            event.setMaxval(doubleMap.get("max"));
        }
        if (value.contains("OnOffParam")) {
            String onOffParam = onOffParam(value);
            event.setAttrtype(1);
            event.setLevel(2);
            event.setEnumval(onOffParam);
        }
        return event;
    }


    private boolean isAdd(String line) {
        for (String error : errorList) {
            if (line.contains(error)) {
                return true;
            }
        }
        return false;
    }

    private String onOffParam(String line) {
        String error = "\'限位\'";
        String error1 = "\'未到位\'";

        try {
            String substring = line.substring(13, line.length() - 2);
            String[] split = substring.split("],");
            for (String s : split) {
                if (s.contains(error) || s.contains(error1)) {
                    String[] split1 = s.split(",");
                    return split1[0].substring(1);
                }
            }
        } catch (Exception e) {
            log.info("onOffParam参数处理异常: ", e);
        }
        return null;
    }

    private String statusParam(String line) {
        String statusParam[] = new String[]{"\'异常\'", "\'断\'", "\'告警\'"};

        String substring = line.substring(14, line.length() - 2);


        //得到每个属性值的枚举型
        String[] split = substring.split("],");
        for (String s : split) {
            String[] split1 = s.split(",");
            for (String s1 : statusParam) {
                try {
                    if (split1[1].contains(s1)) {
                        return split1[0].substring(1);
                    }
                } catch (Exception e) {
                    log.error("statusParam参数处理异常: ", e);
                }
            }
        }
        return "";
    }

    private Map<String, Double> intParam(String line) {
        Map<String, Double> map = new HashMap<>();
        try {
            String substring = line.substring(11, line.length() - 2);
            String[] split = substring.split(",");
            map.put("min", Double.parseDouble(split[0].trim()));
            map.put("max", Double.parseDouble(split[1].trim()));
        } catch (Exception e) {
            log.error("intParam参数梳理异常: ", e);
        }
        return map;
    }

    private Map<String, Double> doubleParam(String line) {
        log.info(line);
        Map<String, Double> map = new HashMap<>();
        String substring = line.endsWith(",") ? line.substring(14, line.length() - 2) : line.substring(14, line.length() - 1);
        String[] split = substring.split(",");
        try {
            if (!"-1.79769313486232E+308".equals(split[0])) {
                map.put("min", Double.parseDouble(split[0].trim()));
                map.put("max", Double.parseDouble(split[1].trim()));
            } else {
                map.put("min", 9999.9999);
                map.put("max", 9999.9999);
            }
        } catch (Exception e) {
            log.error("doubleParam参数处理异常: ", e);
        }
        return map;
    }

    private Map<String, Double> uIntParam(String line) {
        Map<String, Double> map = new HashMap<>();
        try {
            String substring = line.substring(12, line.length() - 2);
            String[] split = substring.split(",");
            map.put("min", Double.parseDouble(split[0].trim()));
            map.put("max", Double.parseDouble(split[1].trim()));
        } catch (Exception e) {
            log.error("uIntParam参数处理异常:", e);
        }
        return map;
    }

    private String getAffectdesc(String line) {
        return line.substring(line.indexOf("[") + 1, line.indexOf("]"));
    }

    private Map<String, String> getDevType() throws IOException {
        Map<String, String> devTyeMap = new HashMap<>();
        String content = FileUtils.readFileToString(new File(devPath));
        MCSDevID mcsDevID = XmlUtils.xmlToBean(content, MCSDevID.class, true, "MCSDevID");
        mcsDevID.getItemsList().forEach(dev -> {
            dev.getItemList().forEach(item -> {
                devTyeMap.put(item.getDevId(), item.getDevIdentity());
            });

        });
        return devTyeMap;
    }
}
